package com.alianzamedica.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.alianzamedica.businessobject.Drug;
import com.alianzamedica.models.ReportModel;

/**
 * @author Carlos
 * 
 */
public class MostSellDrugReport extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7841762811961791821L;

	@SuppressWarnings("unchecked")
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition",
				"attachment;filename=reporte_medicamento.xls");
		ReportModel model = new ReportModel();
		OutputStream out = response.getOutputStream();
		try {
			HSSFWorkbook excel = new HSSFWorkbook();
			HSSFSheet hoja1 = excel.createSheet("hoja 1");
			ArrayList<Drug> list = model.getMostSellDrug();
			Iterator<Drug> iterator = list.iterator();

			HSSFRow row1 = hoja1.createRow(0);
			row1.createCell(0).setCellValue("Id");
			row1.createCell(1).setCellValue("Nombre");
			row1.createCell(2).setCellValue("Codigo");
			row1.createCell(3).setCellValue("Descripción");
			row1.createCell(4).setCellValue("Tipo");
			row1.createCell(5).setCellValue("Nombre Generico");

			int rowNum = 2;
			while (iterator.hasNext()) {
				Drug drug = iterator.next();
				HSSFRow row = hoja1.createRow(rowNum);
				row.createCell(0).setCellValue(object2String(drug.getId()));
				row.createCell(1).setCellValue(object2String(drug.getName()));
				row.createCell(2)
						.setCellValue(object2String(drug.getBarcode()));
				row.createCell(3).setCellValue(
						object2String(drug.getDescription()));
				row.createCell(4).setCellValue(object2String(drug.getType()));
				row.createCell(5).setCellValue(
						object2String(drug.getGenericName()));
				rowNum++;
			}
			excel.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}

	}

	private String object2String(Object object) {
		if (object == null) {
			return "";
		} else {
			return object.toString();
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.processRequest(req, resp);
	}

}
